<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

/**
 * Main service for backoffice display
 */
class m_backoffice_services_BackOfficeService
{
	private static $instance;
	
	private $content;
	private $extraHeader;
	private $title;
    private $js = array();
    private $css = array();
	
	/**
	 * @return m_backoffice_services_BackOfficeService
	 */
	private function __construct()
	{
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return m_backoffice_services_BackOfficeService
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Set extra header in backoffice
	 *
	 * @param string $content
	 */
	public function setExtraHeader($content)
	{
		$this->extraHeader[] = $content;
	}
	
	/**
	 * Retrieve and format extra header(s)
	 *
	 * @return string
	 */
	private function getExtraHeader()
	{
		if(is_array($this->extraHeader) and count($this->extraHeader) > 0)
		{
			return join("\r\n\t\t", $this->extraHeader);	
		}		
		return "";
	}
	
	/**
	 * Set your title for the balise <title>
	 * 
	 * @param string $title
	 */
	public function setTitle($title)
	{
		$this->title = $title;
	}

    public function setJsFromXml()
    {
        $file = f_file_Resolver::getModuleFilePath('backoffice', 'config'.DS.'javascript.xml');

        $els = f_xml_Xpath::getInstance($file)->getElementsFromXpath('src');

        if(!is_null($els) && count($els) > 0)
        {
            foreach($els as $el)
            {
                /* @var $el f_xml_XmlElement */
                if($el->getAttributeValue('type') == 'lib')
                {
                    $filePath = 'js/lib/'.$el->getContent();
                }
                else
                {
                    $filePath = 'themes/'.BACK_THEME.'/backend/js/'.$el->getContent();
                }
                $this->setJs($filePath);
            }
        }
    }

    public function setCssFromXml()
    {
        $file = f_file_Resolver::getModuleFilePath('backoffice', 'config'.DS.'css.xml');

        $els = f_xml_Xpath::getInstance($file)->getElementsFromXpath('src');

        if(!is_null($els) && count($els) > 0)
        {
            foreach($els as $el)
            {
                /* @var $el f_xml_XmlElement */
                $filePath = 'themes/'.BACK_THEME.'/backend/css/'.$el->getContent();
                $this->setCss($filePath);
            }
        }
    }

    public function setCss($css)
    {
        if(is_array($css))
        {
            $this->css = array_merge($this->js, $css);
        }
        else
        {
            $this->css[] = $css;
        }
    }

    public function setJs($js)
    {
        if(is_array($js))
        {
            $this->js = array_merge($this->js, $js);
        }
        else
        {
            $this->js[] = $js;
        }
    }

    public static function getKey()
    {		
        $path = CONFIG_DIR."/.key";

        if(!file_exists($path))
        {
            $key = fopen($path, "w");
            fwrite($key, f_utils_String::generateString(30));
            fclose($key);
        }

        return file_get_contents($path);
    }
		
	/**
	 * Render the backoffice main layout
	 * 
	 * @param string $content main container content
	 * @return string
	 */
	public function renderBackOffice($content, $template = "layouts/Main.html")
	{        
		$templateEngine = f_template_Template::getInstance()->disableCache();
		
		$templateEngine->assign("js", join(",",$this->js));
		$templateEngine->assign("css", join(",",$this->css));
		$templateEngine->assign("extraHeader", $this->getExtraHeader());

		$currentUser = f_context_User::getInstance()->getUser();
		$sUser = f_document_Provider::getInstance()->loadDocuments('users/user')->retrieveFirstDocument();
		$templateEngine->assign("user", $currentUser);
				
		$isSU = !is_null($currentUser) && $sUser->getUniqueId() == $currentUser->getUniqueId() ? true : false;
		$templateEngine->assign("isSU", $isSU);
		
		$templateEngine->assign('menuLinks', $this->getMainMenuLinks($currentUser));

		if(!is_null($content))
		{
			$templateEngine->assign("mainContent", $content);
		}
		
		$templateEngine->setModuleTemplate("backoffice", $template);
		
		$templateEngine->renderDisplay(false);
	}

    private function getMainMenuLinks($user)
    {
        $result = array();

        if(!is_null($user))
        {
            $cookie = f_core_Cookie::getInstance()->setName($user->getLogin());					

            $valuesToGet = array('websiteListWoId' => 'modulewebsiteurl', 'mediasRoot' => 'modulemediasurl', 'usersList' => 'moduleusersurl', 'modulesRoot' => 'modulemodulesurl', 'systemRoot' => 'modulesystemurl');
            $cookieArray = $cookie->getCookie();

            foreach ($valuesToGet as $key => $value)
            {
                if(!is_null($cookieArray))
                {
                    $check_routing = f_core_Routing::getInstance($cookieArray[$value])->setRequestURL($cookieArray[$value]);
                    $request = f_core_Request::getInstance();
                    
                    $docLang = $request->getParameter("docLang");
                    $docId = $request->getParameter("docId");
                    
                    //Check valid URL
                    $doc_checker = f_document_Provider::getInstance();
                    if($doc_checker->checkDocument($docId, $docLang))
                    {
                        $result[$value] = $cookieArray[$value];
                    }
                    else //Invalid ->reset Cookie & Session values
                    {                        
                        $session = f_core_Session::getInstance();
                        $session->setValue($value, f_core_Routing::getInstance()->getUrl($key));
                        $result[$value] = f_core_Routing::getInstance()->getUrl($key);
                        $cookieArray[$value] = f_core_Routing::getInstance()->getUrl($key);
                        f_core_Cookie::getInstance()->setParameters($user->getLogin(), time()+2592000)->setCookie($cookieArray);
                    }
                }
                else
                {
                    $result[$value] = f_core_Routing::getInstance()->getUrl($key);
                }
                
            }
        }

        return $result;
    }

    public static function getAvailableBoLangs()
    {
        $files = f_file_Resolver::getInstance()->fromDirectory(MODULES_DIR.DS.'backoffice'.DS.'locales')->setMask('from_*.*')->setRecursive(true)->find();

        $res = array();
        $result = array();
        
        foreach($files as $file)
        {
            $f = f_file_File::getInstance($file);
            $fName = $f->getFileName();
            $path = explode(DS, $f->getDir());
            $code = str_replace('from_', '', $fName);

            $res[] = end($path);
            $res[] = $code;
        }

        $res = array_unique($res);

        if(count($res) > 0)
        {
            sort($res);
            foreach($res as $iso)
            {
                $l['id'] = $iso;
                $l['label'] = f_locale_Manager::getCultureLabel($iso);
                $result[] = $l;
            }
        }

        return $result;
    }

    /**
     * Get available front themes
     * @return array
     */
    public function getFrontThemes()
    {
        return $this->getThemes();
    }

    /**
     * Get available back themes
     * @return array
     */
    public function getBackThemes()
    {
        return $this->getThemes(true);
    }

    /**
     * Get theme generic method
     * @param boolean $backend
     * @return array
     */
    private function getThemes($backend = false)
    {
        $dirs = f_file_Directory::getInstance(HTTP_DIR.DS.'themes')->getSubdirs();

        $result = array();

        if(count($dirs) > 0)
        {
            foreach($dirs as $dir)
            {
                /* @var $dir f_file_Directory */
                $themes = f_file_Directory::getInstance($dir->getPath())->getSubdirs();
                if(count($themes) > 0)
                {
                    foreach($themes as $theme)
                    {
                        /* @var $theme f_file_Directory */
                        if($backend == true && $theme->getDirName() == 'backend')
                        {
                            $result[] = $dir->getDirName();
                        }
                        else if($theme->getDirName() == 'frontend')
                        {
                            $result[] = $dir->getDirName();
                        }
                    }
                }
            }
        }

        return $result;
    }
}